/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Ding
 * @create 2022/4/14 10:38
 */
public class _0704_二分查找 {
    public static long START_TIME = 0;
    public static long END_TIME = 0;

    public static void main(String[] args) {
        START_TIME = System.currentTimeMillis();
        //调用部分↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
        int[] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 5;
        System.err.println(new _0704_二分查找().binarySearch(nums, target));
        //调用部分↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
        END_TIME = System.currentTimeMillis();
        System.err.println("运行时间：" + (END_TIME - START_TIME) + "ms");
    }

    /**
     * 二分查找
     */
    public int binarySearch(int[] nums, int target) {
        //因为数组角标一定是 0 ~ 长度-1
        int left = 0;
        int right = nums.length - 1;
        //寻找中间值，只要左不大于右，就继续
        while (left <= right){
            //左和右角标的中间
            int mid = (left + right) / 2;
            if (nums[mid] == target){
                //相等，直接return
                return mid;
            }else if (nums[mid] > target){
                //中间值大于目标值，说明要在 左边界~中间值-1 去再次寻找中间值（目标值）
                right = mid - 1;
            }else{
                //中间值小于目标值，说明要在 中间值+1~右边界 去再次寻找中间值（目标值）
                left = mid + 1;
            }
        }
        return -1;
    }


}
